package cn.sdhuijin.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.inject.Inject;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.sdhuijin.dao.BranchDao;
import cn.sdhuijin.dao.UserDao;
import cn.sdhuijin.exception.ExistedException;
import cn.sdhuijin.model.Branch;
import cn.sdhuijin.model.User;
import cn.sdhuijin.tree.branchtree.Node;
import cn.sdhuijin.tree.selecttree.SelectNode;
import cn.sdhuijin.utils.CommonUtil;

/**
 * @author sunp@sdhuijin.cn
 * @version 创建时间：2014年12月25日 上午9:31:35 类说明
 */

@Service
@Transactional
public class BranchServiceImpl implements BranchService {

	@Inject
	private BranchDao branchDao;
	@Inject
	private UserDao userDao;

	@Override
	public void addBranch(Branch branch) {
		Long parentId = null;
		if (branch.getParent() != null) {
			parentId = branch.getParent().getId();
		}
		List<Branch> existedBranch = branchDao.findByParentIdAndName(parentId,
				branch.getName());
		if (existedBranch.size() != 0) {
			throw new ExistedException("对不起，此机构已经存在，无法多次创建!");
		} else {
			branch.setCreateDate(new Date());
			branch.setModifyDate(new Date());
			branchDao.save(branch);
		}
	}

	@Override
	public List<Branch> allBranches() {
		List<Branch> allBranches = branchDao.findAll();
		return allBranches;
	}

	@Override
	public List<Branch> subordinateBranches(Branch branch) {
		List<Branch> tmpBranches = new ArrayList<Branch>();
		List<Branch> subordinateBranches = new ArrayList<Branch>();
		if (branch != null) {
			tmpBranches = branchDao.findByParentId(branch.getId());
			subordinateBranches.addAll(tmpBranches);
			if (tmpBranches.size() == 0) {
				tmpBranches = null;
			} else {
				for (Branch b : tmpBranches) {
					List<Branch> tmp = subordinateBranches(b);
					if (tmp != null) {
						subordinateBranches.addAll(tmp);
					}
				}
			}
		} else {
			subordinateBranches = null;
		}
		return subordinateBranches;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public List<Node> columnTreeNode(Branch branch, Boolean isAdmin) {
		List<Branch> dataList = new ArrayList<Branch>();
		if (isAdmin) {
			dataList = allBranches();
		} else {
			dataList = subordinateBranches(branch);
			dataList.add(branch);
		}
		// 节点列表（散列表，用于临时存储节点对象）
		HashMap<String, Node> nodeList = new HashMap<String, Node>();
		// 根节点
		List<Node> root = new ArrayList<Node>();
		// 根据结果集构造节点列表（存入散列表）
		for (Iterator<Branch> it = dataList.iterator(); it.hasNext();) {
			Branch dataRecord = (Branch) it.next();
			Node node = new Node();
			node.setBranchId(Long.toString(dataRecord.getId()));
			node.setBranchName(dataRecord.getName());
			node.setBranchAddress(dataRecord.getAddress());
			node.setBranchHead(dataRecord.getHead());
			node.setBranchPhone(dataRecord.getPhone());
			node.setBranchRemarks(dataRecord.getRemarks());
			node.setParentId(dataRecord.getParent() == null
					|| dataRecord.getParent().equals("") ? "" : Long
					.toString(dataRecord.getParent().getId()));
			nodeList.put(node.getBranchId(), node);
		}
		// 构造无序的多叉树
		Set<Entry<String, Node>> entrySet = nodeList.entrySet();
		for (Iterator<Entry<String, Node>> it = entrySet.iterator(); it
				.hasNext();) {
			Node node = (Node) ((Map.Entry) it.next()).getValue();
			if (node.getParentId() == null || node.getParentId().equals("")
					|| (Node) nodeList.get(node.getParentId()) == null) {
				root.add(node);
			} else {
				((Node) nodeList.get(node.getParentId())).addChild(node);
			}
		}
		// if (root != null) {
		// root.sortChildren(); // 排序
		// }
		return root;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public List<SelectNode> selectTreeNode(Branch branch, Boolean isAll) {
		List<Branch> dataList = new ArrayList<Branch>();
		if (isAll) {
			dataList = allBranches();
		} else {
			dataList = subordinateBranches(branch);
			dataList.add(branch);
		}
		// 节点列表（散列表，用于临时存储节点对象）
		HashMap<String, SelectNode> nodeList = new HashMap<String, SelectNode>();
		// 根节点
		List<SelectNode> root = new ArrayList<SelectNode>();
		// 根据结果集构造节点列表（存入散列表）
		for (Iterator<Branch> it = dataList.iterator(); it.hasNext();) {
			Branch dataRecord = (Branch) it.next();
			SelectNode node = new SelectNode();
			node.setId(Long.toString(dataRecord.getId()));
			node.setText(dataRecord.getName());
			node.setParentId(dataRecord.getParent() == null
					|| dataRecord.getParent().equals("") ? "" : Long
					.toString(dataRecord.getParent().getId()));
			nodeList.put(node.getId(), node);
		}
		// 构造无序的多叉树
		Set<Entry<String, SelectNode>> entrySet = nodeList.entrySet();
		for (Iterator<Entry<String, SelectNode>> it = entrySet.iterator(); it
				.hasNext();) {
			SelectNode node = (SelectNode) ((Map.Entry) it.next()).getValue();
			if (node.getParentId() == null || node.getParentId().equals("")
					|| (SelectNode) nodeList.get(node.getParentId()) == null) {
				root.add(node);
			} else {
				((SelectNode) nodeList.get(node.getParentId())).addChild(node);
			}
		}
		// if (root != null) {
		// root.sortChildren(); // 排序
		// }
		return root;
	}

	/**
	 * 
	 * @param currentId
	 *            当前列（从0开始）
	 * @param branchLength
	 *            机构的深度（当前为总行、支行、网点，故为3）
	 * @param userId
	 *            用户手机号所在的列（从0开始，这里是第7列，故为6）
	 * @param parentId
	 *            机构上级机构or用户所属机构的id
	 * @param lo
	 *            excel表格取出来的row的列表
	 * @return
	 */
	@Transactional
	public Boolean importSave(int currentId, int branchLength, int userId,
			Long parentId, List<Object> lo) throws Exception {
		Boolean flag = false;
		String name = lo.get(currentId).toString().trim();
		if (CommonUtil.allIsNotEmpty(name)) {
			List<Branch> existedBranch = branchDao.findByParentIdAndName(
					parentId, name);
			Branch branch = new Branch();
			Branch parentBranch = new Branch();
			Long nParentId = null;
			User user = new User();
			if (currentId < branchLength) {
				if (existedBranch.size() == 0) {
					if (parentId != null) {
						parentBranch = branchDao.findOne(parentId);
					} else {
						parentBranch = null;
					}
					branch.setParent(parentBranch);
					branch.setName(name);
					branch.setCreateDate(new Date());
					branch.setModifyDate(new Date());
					nParentId = branchDao.save(branch).getId();
				} else {
					nParentId = existedBranch.get(0).getId();
				}
				if (currentId == branchLength - 1) {
					Branch currentBranch = branchDao.findOne(nParentId);
					currentBranch.setHead(lo.get(branchLength).toString());
					currentBranch.setPhone(lo.get(branchLength + 1).toString());
					currentBranch.setAddress(lo.get(branchLength + 2)
							.toString());
					currentBranch.setRemarks(lo.get(branchLength + 3)
							.toString());
					branch.setCreateDate(new Date());
					branch.setModifyDate(new Date());
					branchDao.save(currentBranch);
					importSave(userId, branchLength, userId, nParentId, lo);
					flag = true;
				} else {
					Boolean notnull = importSave(currentId + 1, branchLength,
							userId, nParentId, lo);
					if (!notnull) {
						Branch currentBranch = branchDao.findOne(nParentId);
						currentBranch.setHead(lo.get(branchLength).toString());
						currentBranch.setPhone(lo.get(branchLength + 1)
								.toString());
						currentBranch.setAddress(lo.get(branchLength + 2)
								.toString());
						currentBranch.setRemarks(lo.get(branchLength + 3)
								.toString());
						branch.setCreateDate(new Date());
						branch.setModifyDate(new Date());
						branchDao.save(currentBranch);
						importSave(userId, branchLength, userId, nParentId, lo);
						flag = true;
					}
				}
			} else if (currentId == userId) {
				List<User> existedUser = userDao.findByBranchIdAndTelphone(
						parentId, name);
				if (existedUser.size() == 0) {
					user.setTelphone(lo.get(currentId).toString());
					parentBranch = branchDao.findOne(parentId);
					user.setBranch(parentBranch);
					user.getBranch().setId(parentId);
				} else {
					user = existedUser.get(0);
				}
				user.setName(lo.get(userId + 1).toString());
				user.setSex(lo.get(userId + 2).toString());
				user.setAge(lo.get(userId + 3).toString());
				user.setUserType(lo.get(userId + 4).toString());
				user.setEmail(lo.get(userId + 5).toString());
				userDao.save(user);
			}
			flag = true;
		} else {
			flag = false;
		}
		return flag;
	}

	@Override
	public void BatchImport(List<List<Object>> llo) throws Exception {
		if (llo != null) {
			for (int i = 1; i < llo.size(); i++) {
				importSave(0, 3, 7, null, llo.get(i));
			}
		}
	}

	@Override
	public Branch searchOne(String selectId) {
		Long id = Long.parseLong(selectId);
		return branchDao.findOne(id);
	}

	@Override
	public List<Branch> getBranchSelectList() {
		Branch firstLevelBranch = branchDao.findByParentIdIsNull();
		List<Long> branchIds = new ArrayList<Long>();
		List<Branch> secondLevelBranchList = new ArrayList<Branch>();
		if (firstLevelBranch != null) {
			branchIds.add(firstLevelBranch.getId());
			secondLevelBranchList = branchDao.findByParentIdIn(branchIds);
		}
		return secondLevelBranchList;
	}

	@Override
	public void updateBranch(Branch branch) throws Exception {
		if (branch.getId() != null) {
			Branch uBranch = branchDao.findOne(branch.getId());
			if (uBranch == null) {
				throw new Exception("未找到此机构记录，无法更新！");
			} else {
				uBranch.setName(branch.getName());
				uBranch.setHead(branch.getHead());
				uBranch.setPhone(branch.getPhone());
				uBranch.setAddress(branch.getAddress());
				uBranch.setRemarks(branch.getRemarks());
				branchDao.save(uBranch);
			}
		} else {
			throw new Exception("机构参数获取失败，无法更新！");
		}
	}
}
